package com.hp.provider.config;

import com.hp.common.annotation.AllowedValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Objects;

/**
 * 自定义 检验规则
 *
 * @author <a href="mailto:xing.dong@sha.ontime-express.com">Xavier Dong</a>
 * @date
 */
public class AllowedValueValidator implements ConstraintValidator<AllowedValue, Long> {

    private long[] allowedValues;

    @Override
    public void initialize(AllowedValue constraintAnnotation) {
        this.allowedValues = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(Long value, ConstraintValidatorContext context) {
        if (allowedValues.length == 0) {
            return true;
        }
        return Arrays.stream(allowedValues).anyMatch(o -> Objects.equals(o, value));
    }
}